<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Vue构造函数</title>
</head>
<body>
    <div id="app">
        <input type="text" id="a" v-model='text'>
        {{text}}
    </div>

    <script>  
        var vm = new Vue({
            el:'#app',
            data:{
                text:'hello word'
            }
        })
        
        function Vue(options){
            this.el = options.el;
            this.data = options.data;
            var nodes = document.querySelector(this.el);
            var dom = node2fragment(nodes,this.data);
            nodes.appendChild(dom);
        }
        Vue.prototype = {

        }
        //遍历编译节点插入碎片
        function node2fragment(node,obj){
            var child;
            var fragment = document.createDocumentFragment();
            while(child = node.firstChild){
                compile(child,obj)
                fragment.appendChild(child)
                
            }
            return fragment;
        }

        //编译节点
        function compile(node,obj){
            var type = node.nodeType;
            //1为元素节点 3为文本节点
            if(type==1){
                //去属性集合
                var attrs = node.attributes;
                for (let index = 0; index < attrs.length; index++) {
                    if(attrs[index].nodeName=="v-model"){
                        var name = attrs[index].nodeValue;
                        node.value = obj[name];
                    } 
                }
            }else if(type==3){
                //匹配获取name
                var reg = /\{\{(.*)\}\}/;
                if(reg.test(node.nodeValue)){
                    var name = RegExp.$1.trim();
                    node.nodeValue = obj[name];
                }
            }
        }
    </script>
</body>
</html>